<template>
  <div>
    <el-card
      shadow="always"
      :body-style="{ padding: '20px' }"
      style="margin: 20px"
    >
      <el-form :inline="true" size="normal">
        <el-form-item>
          <el-input placeholder="用户名" v-model="searchName" size="default"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="searchBtn"
            >查询</el-button
          >
          <el-button size="small" @click="removeSearch">清空</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" size="small" @click="addBtn">添加</el-button>
        <el-button type="danger" size="small" @click="">批量删除</el-button>
      </div>
      <el-table border stripe style="margin: 20px 0" :data="userInfoList">
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" width="50" label="序号" align="center" />
        <el-table-column
          label="用户名"
          width="120"
          prop="username"
        ></el-table-column>
        <el-table-column
          label="用户昵称"
          width="120"
          prop="nickName"
        ></el-table-column>
        <el-table-column
          label="角色列表"
          width="200"
          prop="roleName"
        ></el-table-column>
        <el-table-column
          label="创建时间"
          width="150"
          prop="gmtCreate"
        ></el-table-column>
        <el-table-column
          label="更新时间"
          width="150"
          prop="gmtModified"
        ></el-table-column>
        <el-table-column
          label="操作"
          align="center"
          fixed="right"
          width="200px"
        >
          <template v-slot="{ row }">
            <el-button
              type="info"
              icon="el-icon-user"
              size="mini"
              @click="setUserRoleBtn(row)"
            ></el-button>
            <el-button
              style="margin: 0 15px"
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUserBtn(row)"
            ></el-button>
            <el-popconfirm
              title="这是一段内容确定删除吗？"
              @onConfirm="deleteBtn(row.id)"
            >
              <el-button
                slot="reference"
                type="danger"
                icon="el-icon-delete"
                size="mini"
              ></el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page.sync="currentPage"
        :page-sizes="[3, 5, 8, 10]"
        :page-size.sync="pageSize"
        :total="total"
        background
        layout=" sizes, prev, pager, next, jumper"
      >
      </el-pagination>
    </el-card>
    <!-- 添加或修改用户信息弹窗 -->
    <el-dialog
      :title="addOrUpdateUser.id ? '修改角色' : '添加角色'"
      :visible.sync="isAddOrUpdateUserDialog"
      width="60%"
    >
      <el-form
        :model="addOrUpdateUser"
        :rules="rules"
        ref="addOrUpdateUser"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="addOrUpdateUser.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="addOrUpdateUser.nickName"></el-input>
        </el-form-item>
        <el-form-item
          label="用户密码"
          prop="password"
          v-if="!addOrUpdateUser.id"
        >
          <el-input v-model="addOrUpdateUser.password"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="resetForm('addOrUpdateUser')">取消</el-button>
          <el-button type="primary" @click="submitForm('addOrUpdateUser')"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 设置角色弹窗 -->
    <el-dialog title="设置角色" :visible.sync="isSetUserDialog" width="60%">
      <el-form label-width="100px" :inline="false" size="normal">
        <el-form-item label="用户名">
          <el-input :value="userName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="checkedCities"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="city in cities"
              :label="city.id"
              :key="city.id"
              >{{ city.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span>
          <el-button @click="isSetUserDialog = false">取消</el-button>
          <el-button type="primary" @click="saveBtn">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  reqUserList,
  reqAddUser,
  reqUpdataUser,
  reqUserAssignById,
  reqAddUserToAssign,
  reqDeleteUser,
} from "@/api/auth/user";
export default {
  name: "User",
  data() {
    return {
      currentPage: 1, //当前页码
      pageSize: 5, //当前连续页
      total: 0, //总条数
      userInfoList: [], //初始数据列表
      searchName:"",
      addOrUpdateUser: {
        //新增或者修改用户初始数据
        username: "",
        password: "",
        nickName: "",
      },
      userId: null, //当前角色id
      userName: "",
      rules: {
        //表单校验规则
        username: [{ required: true, message: "用户名称", trigger: "blur" }],
        password: [
          { required: true, message: "用户密码", trigger: "blur" },
          { min: 3, max: 12, message: "长度在 2 到 12个字符", trigger: "blur" },
        ],
        nickName: [{ required: true, message: "用户名称", trigger: "blur" }],
      },
      isAddOrUpdateUserDialog: false, //控制添加用户或者更新用户弹窗，
      isSetUserDialog: false, //控制设置角色弹窗
      /**---------------------------------- */
      checkAll: false,
      checkedCities: [],
      cities: [],
      isIndeterminate: true,
    };
  },
  methods: {
    //初始化列表数据
    async initUserInfoListData() {
      try {
        const result = await reqUserList(this.currentPage, this.pageSize);
        this.total = result.total;
        this.userInfoList = result.items;
      } catch (error) {
        this.$message({
          message: error.message,
          type: "error",
        });
      }
    },
    //添加角色或更新角色表单校验及提交回调函数
    async submitForm(addOrUpdateUser) {
      this.$refs[addOrUpdateUser].validate(async (valid) => {
        if (valid) {
          if (this.addOrUpdateUser.id) {
            await reqUpdataUser(this.addOrUpdateUser);
            this.$message({
              message: "恭喜你，修改用户成功",
              type: "success",
            });
          } else {
            await reqAddUser(this.addOrUpdateUser);
            this.$message({
              message: "恭喜你，添加用户成功",
              type: "success",
            });
          }
          this.initUserInfoListData(); //重新获取数据
        } else {
          this.$message({
            message: "校验出错，请检查！",
            type: "error",
          });
          return false;
        }
        this.isAddOrUpdateUserDialog = false;
      });
    },
    //清空表单校验
    resetForm(addOrUpdateUser) {
      this.isAddOrUpdateUserDialog = false;
      this.$refs[addOrUpdateUser].resetFields();
    },
    //点击添加按钮事件回调
    addBtn() {
      this.isAddOrUpdateUserDialog = true;
      this.$nextTick(() => {
        this.$refs["addOrUpdateUser"].resetFields();
      });
      setTimeout(() => {
        this.addOrUpdateUser = {
          //数据重置
          username: "",
          password: "",
          nickName: "",
        };
      }, 0);
    },
    //点击修改用户事件回调函数
    editUserBtn(row) {
      this.isAddOrUpdateUserDialog = true;
      this.$nextTick(() => {
        this.$refs["addOrUpdateUser"].resetFields();
      });
      setTimeout(() => {
        this.addOrUpdateUser = row;
      }, 0);
    },
    //点击设置用户角色信息按钮事件回调
    async setUserRoleBtn(row) {
      this.isSetUserDialog = true;
      this.userId = row.id;
      this.userName = row.username;
      try {
        const result = await reqUserAssignById(row.id);
        this.checkedCities = result.assignRoles.map((item) => item.id);
        this.cities = result.allRolesList;
      } catch (error) {
        this.$message({
          message: error.message,
          type: "error",
        });
      }
    },
    handleCheckAllChange(val) {
      this.checkedCities = val ? this.cities.map((item) => item.id) : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cities.length;
    },
    //点击确认提交按钮
    async saveBtn() {
      try {
        const strArr = this.checkedCities.toString();
        await reqAddUserToAssign(this.userId, strArr);
        this.$message({
          message: "恭喜你，设置用户角色成功！",
          type: "success",
        });
        this.initUserInfoListData();
      } catch (error) {
        this.$message({
          message: error.message,
          type: "error",
        });
      }
      this.isSetUserDialog = false;
    },
    //点击删除按钮
    async deleteBtn(id) {
      try {
        await reqDeleteUser(id);
        this.$message({
          message: "恭喜你，删除成功",
          type: "success",
        });
        this.initUserInfoListData();
      } catch (error) {
        this.$message({
          message: error.message,
          type: "error",
        });
      }
    },
    //点击搜索按钮
    async searchBtn(){
      try {
        const result = await reqUserList(this.currentPage, this.pageSize,this.searchName);
        this.total = result.total;
        this.userInfoList = result.items;
      } catch (error) {
        this.$message({
          message: error.message,
          type: 'error'
        })
      }
    },
    //点击清除按钮
    removeSearch(){
      this.searchName = ""
      this.initUserInfoListData()
    }
  },
  mounted() {
    this.initUserInfoListData();
  },
  watch: {
    currentPage() {
      this.initUserInfoListData();
    },
    pageSize() {
      this.initUserInfoListData();
    },
  },
};
</script>

<style lang="scss" scoped></style>
